import { BoundingRect, EventMap } from '../module/event'
import { Point2D } from '../point'

export interface IShape {
  draw(ctx: CanvasRenderingContext2D): void
  isPointInClosedRegion(point: Point2D): boolean
  on<T extends keyof EventMap>(eventName: T, listener: (event: EventMap[T]) => void): void
  off<T extends keyof EventMap>(eventName: T, listener: (event: EventMap[T]) => void): void
  setPosition(position: Point2D): void
  setPosition(x: number, y: number): void
}

export class Shape implements IShape {
  static update: string = null

  id: string = crypto.randomUUID()
  listenerMap: Map<keyof EventMap, Array<(event: any) => void>> = new Map()
  boundingRect: BoundingRect

  draw(ctx: CanvasRenderingContext2D): void {}

  isPointInClosedRegion(point: Point2D): boolean {
    return false
  }

  on<T extends keyof EventMap>(eventName: T, listener: (event: EventMap[T]) => void) {
    if (this.listenerMap.has(eventName)) {
      this.listenerMap.get(eventName)?.push(listener)
    } else {
      this.listenerMap.set(eventName, [listener])
    }
  }

  off<T extends keyof EventMap>(eventName: T, listener: (event: EventMap[T]) => void) {
    if (this.listenerMap.has(eventName)) {
      const listeners = this.listenerMap.get(eventName) || []
      const index = listeners.findIndex((cacheListener) => cacheListener === listener)
      if (index !== -1) {
        listeners.splice(index, 1)
      }
    }
  }

  setPosition(position: Point2D): void
  setPosition(x: number, y: number): void
  setPosition(x: any, y?: any): void {}
}
